package cn.toolck.minitomcat.runner;

import cn.toolck.minitomcat.pojo.Request;
import cn.toolck.minitomcat.pojo.Response;
import cn.toolck.minitomcat.servlet.HttpServlet;
import cn.toolck.minitomcat.servlet.Servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName WorkRunner
 * @Description TODO
 * @Author Toolck Rin
 * @Date 2021/3/17 23:05
 * @Version 1.0
 **/
public class WorkRunner implements Runnable {
    private Socket socket;
    private Map<String, HttpServlet> servletMap;

    public WorkRunner(Socket socket, Map<String, HttpServlet> servletMap) {
        this.socket = socket;
        this.servletMap = servletMap;
    }

    public WorkRunner() {
    }

    @Override
    public void run() {
        InputStream in = null;
        try {
            in = socket.getInputStream();
            OutputStream out = socket.getOutputStream();
            Request request = new Request(in);
            System.out.println(request.getUrl());
            Response response = new Response(out);
            String url = request.getUrl();
            if (!servletMap.containsKey(url)) {
                response.outputHtml(url);
            } else {
                HttpServlet servlet = servletMap.get(url);
                servlet.service(request, response);
            }
            out.flush();
            //关闭
            out.close();
            in.close();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
